package cn.yuanqiao.archive.appManager.service.impl;

import cn.yuanqiao.archive.appManager.domain.TenantCategory;
import cn.yuanqiao.archive.appManager.domain.YqdaTrees;
import cn.yuanqiao.archive.appManager.mapper.TenantCategoryMapper;
import cn.yuanqiao.archive.appManager.mapper.YqdaTreesMapper;
import cn.yuanqiao.common.core.domain.TreeSelect;
import cn.yuanqiao.archive.appManager.service.ITenantFondsService;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.bean.BeanValidators;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.manage.domain.ManageFonds;
import cn.yuanqiao.manage.mapper.ManageFondsMapper;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;

@Service
public class TenantFondsServiceImpl implements ITenantFondsService {

    private static final Logger log = LoggerFactory.getLogger(TenantFondsServiceImpl.class);

    @Autowired
    private ManageFondsMapper manageFondsMapper;
    @Autowired
    private TenantCategoryMapper categoryMapper;
    @Autowired
    private YqdaTreesMapper treesMapper;
    @Autowired
    protected Validator validator;

    /**
     * 查询租户全宗管理
     *
     * @param ID 租户全宗管理主键
     * @return 租户全宗管理
     */
    @Override
    public ManageFonds selectManageFondsByID(String ID)
    {
        return manageFondsMapper.selectManageFondsByID(ID);
    }

    /**
     * 查询租户全宗管理列表
     *
     * @param manageFonds 租户全宗管理
     * @return 租户全宗管理
     */
    @Override
    public List<ManageFonds> selectManageFondsList(ManageFonds manageFonds)
    {
        String fondsName = manageFonds.getFondsName();
        if(StringUtils.isNotEmpty(fondsName) && !"null".equals(fondsName) && fondsName.contains("_")){
            fondsName = fondsName.replace("_","\\_");
            manageFonds.setFondsName(fondsName);
        }
        return manageFondsMapper.selectManageFondsList(manageFonds);
    }

    @Override
    public List<TreeSelect> treeList() {
        String tenantCode = SecurityUtils.getTenantCode();
        List<ManageFonds> manageFonds = manageFondsMapper.selectFondsCodeByTenantCode(tenantCode);
        TreeSelect rootTree = new TreeSelect();
        rootTree.setId(0L);
        rootTree.setLabel("根节点");
        rootTree.setNodeType("root");
        List<TreeSelect> chilTrees = new ArrayList<>();
        for(ManageFonds mf:manageFonds){
            TreeSelect chilTree = new TreeSelect();
            chilTree.setId(mf.getId());
            chilTree.setLabel(mf.getFondsName());
            chilTree.setFondsCode(mf.getFondsCode());
            chilTree.setTenantCode(mf.getTenantCode());
            chilTree.setNodeType("fonds");
            chilTrees.add(chilTree);
        }
        rootTree.setChildren(chilTrees);
        List<TreeSelect> treeSelects = new ArrayList<>();
        treeSelects.add(rootTree);
        return treeSelects;
    }

    /**
     * 新增租户全宗管理
     *
     * @param manageFonds 租户全宗管理
     * @return 结果
     */
    @Override
    public int insertManageFonds(ManageFonds manageFonds)
    {
        manageFonds.setCreateTime(DateUtils.getNowDate());
        ManageFonds manageFonds1 = new ManageFonds();
        manageFonds1.setFondsCode(manageFonds.getFondsCode());
        manageFonds1.setTenantCode(manageFonds.getTenantCode());
        List<ManageFonds> manageFonds2 = manageFondsMapper.selectManageFondsList(manageFonds1);
        if(manageFonds2!=null && manageFonds2.size()>0){
            throw new ServiceException("全宗号不能重复");
        }
        return manageFondsMapper.insertManageFonds(manageFonds);
    }

    /**
     * 修改租户全宗管理
     *
     * @param manageFonds 租户全宗管理
     * @return 结果
     */
    @Override
    public int updateManageFonds(ManageFonds manageFonds)
    {
        manageFonds.setUpdateTime(DateUtils.getNowDate());
        ManageFonds manageFonds3 = manageFondsMapper.selectManageFondsByID(manageFonds.getId().toString());
        if(!manageFonds3.getFondsCode().equals(manageFonds.getFondsCode())){  //没有变
            ManageFonds manageFonds1 = new ManageFonds();
            manageFonds1.setFondsCode(manageFonds.getFondsCode());
            manageFonds1.setTenantCode(manageFonds.getTenantCode());
            List<ManageFonds> manageFonds2 = manageFondsMapper.selectManageFondsList(manageFonds1);
            if(manageFonds2!=null && manageFonds2.size()>0){
                throw new ServiceException("全宗号不能重复");
            }
        }
        return manageFondsMapper.updateManageFonds(manageFonds);
    }

    /**
     * 批量删除租户全宗管理
     *
     * @param IDs 需要删除的租户全宗管理主键
     * @return 结果
     */
    @Override
    public int deleteManageFondsByIDs(String[] IDs)
    {
        return manageFondsMapper.deleteManageFondsByIDs(IDs);
    }

    /**
     * 删除租户全宗管理信息
     *
     * @param ID 租户全宗管理主键
     * @return 结果
     */
    @Override
    public int deleteManageFondsByID(String ID)
    {
        return manageFondsMapper.deleteManageFondsByID(ID);
    }

    @Override
    public String importFonds(List<ManageFonds> manageList, Boolean isUpdateSupport, String operName,String tenantId) {

        if (StringUtils.isNull(manageList) || manageList.size() == 0)
        {
            throw new ServiceException("导入全宗数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (ManageFonds fond : manageList)
        {
            try
            {
                fond.setCreateBy(operName);
                fond.setTenantId(tenantId);
                BeanValidators.validateWithException(validator, fond);
                manageFondsMapper.insertManageFonds(fond);
                successNum++;
                successMsg.append("<br/>" + successNum + "、全宗号 " + fond.getFondsCode() + " 导入成功");
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、全宗号 " + fond.getFondsCode() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();

    }

    @Override
    @Transactional
    public void initFonds(String fondsCode, String fondsName) {
        String tenantCode = SecurityUtils.getTenantCode();
        //先查询全宗数量
        List<ManageFonds> list = manageFondsMapper.selectFondsCodeByTenantCode(tenantCode);
        if(list.size() == 1){
            //修改全宗
            manageFondsMapper.updateManageFondsInit(fondsCode,fondsName,tenantCode);
            //修改门类
            categoryMapper.updateFondsTenantCategory(fondsCode,new TenantCategory().getTableName());
            //修改门类树
            treesMapper.updateFonds(fondsName,new YqdaTrees().getTableName());
        }else if(list.size() == 0){
            ManageFonds manageFonds = new ManageFonds();
            manageFonds.setCreateTime(DateUtils.getNowDate());
            manageFonds.setFondsCode(fondsCode);
            manageFonds.setFondsName(fondsName);
            manageFonds.setStatus("1");
            manageFonds.setTenantCode(tenantCode);
            manageFondsMapper.insertManageFonds(manageFonds);
        }else {
            throw new ServiceException("请核对全宗个数(MANAGE_FONDS)");
        }

    }
}
